<template>
  <div class="masking" v-show="visible">
    <div class="addPhotoContainer"></div>
    <div class="addController">
      <h3 class="addTitle">
        上传照片-普通上传(H5)<span class="close" @click="close">╳</span>
      </h3>
      <div class="photoTitles">
        <span class="uploadTo">上传到</span>
        <div class="photoSelect">
          <img class="showPhoto" src="public/img/1.jpg" />
          相册名称
        </div>
      </div>

      <!-- 上传按钮 -->
      <div class="showContainer" v-show="!showLoadContainer">
        <div class="uploadContainer">
          <span class="fileinput-button">
            <span>上传图片</span>
            <input
              class="imgFile"
              type="file"
              name=""
              multiple="multiple"
              @input="addImg"
            />
          </span>
          <span class="hint"> 按住Ctrl可多选 </span>
        </div>
      </div>

      <!-- 显示待上传图片  -->
      <div class="loadContainer" v-show="showLoadContainer">
        <div class="wantUpload">
          <template v-for="(item, index) in wantUploadPhotos">
            <UploadPhotoItem :item="item" :key="index"></UploadPhotoItem>
          </template>
        </div>
        <div class="addStyle">
          <!-- <span class="fileinput-add">
              <span></span>
              <input class="imgFile-add" type="file" multiple="multiple" />
            </span> -->
        </div>
        <!-- 开始上传按钮 -->
        <div class="bottomStyle">
          <span class="uploadBtn" @click="startUpload">开始上传</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import UploadPhotoItem from "./UploadPhotoItem.vue";
import { apiUpload } from "../api";
export default {
  props: ["visible"],
  components: {
    UploadPhotoItem,
  },
  data() {
    return {
      wantUploadPhotos: [],
    };
  },
  computed: {
    showLoadContainer() {
      return this.wantUploadPhotos.length > 0;
    },
  },
  methods: {
    async startUpload() {
      // 串行
      for (const photo of this.wantUploadPhotos) {
        await apiUpload(photo);
      }

      // 并行
      // Promise.all
      //   const promises = this.wantUploadPhotos.map((photo) => apiUpload(photo));
      //   await Promise.all(promises);

      // reset
      // 《重构》
      // 《代码大全》
      // 写好代码的原则
      // 1. 表达出代码的意图
      // 2. 不可以有重复
      this.reset();
      this.uploadCompleted();
    },

    uploadCompleted() {
      this.$emit("upload-completed");
    },

    reset() {
      this.wantUploadPhotos = [];
    },

    close() {
      this.$emit("update:visible", false);
    },
    addImg(e) {
      this.wantUploadPhotos.push(...e.target.files);
    },
  },
};
</script>

<style></style>
